﻿using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using Microsoft.AspNetCore.Html;

namespace FDSimpleModelGenerator.Common.Mvc
{
    /// <summary>
    /// Html扩展
    /// </summary>
    public static class HtmlExtensions
    {
        /// <summary>
        /// 引入文件
        /// </summary>
        /// <param name="html"></param>
        /// <param name="type"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static IHtmlContent Include(this IHtmlHelper html, string type, string fileName)
        {
            var env = html.ViewContext.HttpContext.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment;
            var root = env.WebRootPath;
            var tempFileName = fileName;
            if (fileName.StartsWith("/") || fileName.StartsWith("~/"))
            {
                fileName = fileName.Replace("~", "");
                tempFileName = Path.Combine(root, fileName.TrimStart('/'));
            }
            if (!File.Exists(tempFileName))
                throw new FileNotFoundException(tempFileName);
            var fi = new FileInfo(tempFileName);
            var res = $"{fileName}?r={fi.LastWriteTime.Ticks}";
            if ("script".Equals(type, StringComparison.OrdinalIgnoreCase))
            {
                return html.Raw($"<script src=\"{res}\"></script>");
            }
            if ("link".Equals(type, StringComparison.OrdinalIgnoreCase))
            {
                return html.Raw($"<link href = \"{res}\" rel=\"stylesheet\" />");
            }

            return html.Raw(fileName);
        }

        /// <summary>
        /// 引入script文件
        /// </summary>
        /// <param name="html"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static IHtmlContent InclueScript(this IHtmlHelper html, string fileName)
        {
            return html.Include("script", fileName);
        }

        /// <summary>
        /// 引入css文件
        /// </summary>
        /// <param name="html"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static IHtmlContent InclueCss(this IHtmlHelper html, string fileName)
        {
            return html.Include("link", fileName);
        }
    }
}
